#!/usr/local/bin/php
<?php
require_once 'common.php';

global $logger;
global $dbOAIICust;
global $dbOAIICode;
global $codeModel;

$options = getopt('a:f:c:s');
if (empty($options)) {
    $logger->err("usage: " . basename(__FILE__) . " [-a import|delete] [-f company_list_file|-c company_id] -s");
    exit();
}
if (isset($options['a'])) {
    $action = $options['a'];
} else {
    $action = 'import';
}
if (!in_array($action, array('import', 'delete'))) {
    $logger->err("wrong action");
    exit();
}
if (isset($options['f'])) {
    $contents = file_get_contents($options['f']);
    if ($contents === false) {
        $logger->err("get file contents failed");
        exit();
    }
} else if (isset($options['c'])) {
    $contents = $options['c'];
} else {
    $logger->err("no company specified");
    exit();
}
if (isset($options['s'])) {
	$checkConflict = false;
} else {
	$checkConflict = true;
}

$rows = explode("\n", trim($contents));
if ($action == 'import') {
    foreach ($rows as $row) {
        $row = explode("\t", trim($row));
        $companyId = isset($row[0]) ? intval($row[0]) : 0;
        
        if (!importCompany($companyId, $checkConflict)) {
            $logger->err("import company failed: company-$companyId");
            continue;
        }
        $logger->info("import company succeed: company-$companyId");
    }
} else if ($action == 'delete') {
    foreach ($rows as $row) {
        $row = explode("\t", trim($row));
        $companyId = isset($row[0]) ? intval($row[0]) : 0;
        
        if (!deleteCompany($companyId)) {
            $logger->err("delete company failed: company-$companyId");
            continue;
        }
        $logger->info("delete company succeed: company-$companyId");
    }
}
